import { PrismaClient } from '@prisma/client';

// 创建全局Prisma客户端实例
let prisma: PrismaClient;

declare global {
  var __prisma: PrismaClient | undefined;
}

// 在开发环境中使用全局变量避免热重载时创建多个连接
if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient();
} else {
  if (!global.__prisma) {
    global.__prisma = new PrismaClient({
      log: ['query', 'info', 'warn', 'error'],
    });
  }
  prisma = global.__prisma;
}

// 优雅关闭数据库连接
process.on('beforeExit', async () => {
  await prisma.$disconnect();
});

process.on('SIGINT', async () => {
  await prisma.$disconnect();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  await prisma.$disconnect();
  process.exit(0);
});

export { prisma };
export default prisma;

// 导出Prisma类型以便在其他地方使用
export type {
  User,
  Channel,
  Video,
  ChatRoom,
  ChatMessage,
  LiveRoom,
  LiveMessage,
  Gift,
  GiftSend,
  UserWallet,
  PointLedger,
  BankAccount,
  Recharge,
  Withdrawal,
  Notice,
  Faq,
  UserRole,
  UserStatus,
  MemberLevel,
  VideoVisibility,
  VideoStatus,
  ChatRoomStatus,
  LiveRoomStatus,
  RechargeMethod,
  ReviewStatus,
  LedgerReason,
  LedgerRelated
} from '@prisma/client';
